package com.logic.landseaserver.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.logic.common.exception.BusinessException;
import com.logic.common.util.PagingTool;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.util.FopReport;
import com.logic.landseaserver.domain.Check;
import com.logic.landseaserver.domain.ReportData;
import com.logic.landseaserver.service.ICheckService;
import com.logic.landseaserver.service.IPDFGenerationService;

@Service
public class PDFGenerationServiceImpl implements IPDFGenerationService, EnvironmentAware {
	private Logger logger = LoggerFactory.getLogger(PDFGenerationServiceImpl.class);
	private static RelaxedPropertyResolver propertyResolver;
	private static final String ENV_FILE_PATH = "logic.file.path.";
	private static final String LOCAL_PATH = "local";
	private static final String REMOTE_PATH = "remote";

	private String localPath = null;
	private String remotePath = null;

	@Autowired
	private ICheckService checkServiceImpl;

	@Override
	public String getCheckReport(Integer taskID) throws IOException, BusinessException {
		String pdf_url = null;
		StringBuffer pdfFileName = new StringBuffer();
		pdfFileName
		.append("Check").append("-").append(System.currentTimeMillis()).append(".pdf");
			pdf_url = getPDFRemotePath(pdfFileName.toString());
			QueryUtil queryUtil = new QueryUtil();
			PagingTool pagingTool = new PagingTool();
			pagingTool.setCurrentPage(1);
			pagingTool.setPageSize(-1);
			queryUtil.setPagingTool(pagingTool);
			List<Check> checkList = (List<Check>) checkServiceImpl.query(queryUtil);

			StringBuffer buf = new StringBuffer();
			buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			buf.append("<Report>");
			buf.append(" <ReportHeader>");
			buf.append("<Title>");
			buf.append("<Sub>检查表</Sub>");
			buf.append("<PNO><![CDATA[" + "测试项目" + "]]></PNO>"
						+ "<MNAME><![CDATA[" + "李红" + "]]></MNAME>");
			buf.append("</Title>");
			buf.append(" </ReportHeader>");
			buf.append(" <ReportBody>");
			buf.append(" <Table>");
			if (checkList != null && checkList.size() > 0) {
				for (Check check : checkList) {
					buf.append("<Record>"
							+ "<checkName><![CDATA[" + this.null2Blank(check.getName()) + "]]></checkName>"
							+ "<checkDesc><![CDATA[" + this.null2Blank(check.getDescription()) + "]]></checkDesc>"
							+ "</Record>");
				}
			}
			buf.append(" </Table>");
			buf.append(" </ReportBody>");
			buf.append(" <ReportFooter>");
			buf.append(" </ReportFooter>");
			buf.append("</Report>");

			pdf_url = pdfGeneratorForWeeklyReport(buf, pdfFileName.toString(), localPath + "/fop_config");
			return pdf_url;
	}

	private String pdfGeneratorForWeeklyReport(StringBuffer buf, String pdfFileName, String fopConfigPath)  throws IOException{
		String pdf_url = null;
		ReportData data = null;
		FileOutputStream fos = null;
		File file = new File(fopConfigPath + "/report/fop_xsl/check.xsl");
		if (file != null) {
			try {
				data = FopReport.createReport(file.toString(), buf.toString().getBytes("UTF-8"), fopConfigPath);
				fos = new FileOutputStream(localPath + "/" + pdfFileName);
				pdf_url = remotePath + "/" + pdfFileName;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (data != null) {
					fos.write(data.getData());
					fos.close();
				}
			}
		}
		return pdf_url;
	}

	private String null2Blank(String str) {
		String result = "";
		if (StringUtils.isNotBlank(str)) {
			result = str;
		}
		return result;
	}

	private String getPDFRemotePath(String fileName){
		return new StringBuilder().append(remotePath).append(File.separator).append(fileName).toString();
	}

	@Override
	public void setEnvironment(Environment environment) {
		propertyResolver = new RelaxedPropertyResolver(environment, ENV_FILE_PATH);
		localPath = propertyResolver.getProperty(LOCAL_PATH, String.class, null);
		remotePath = propertyResolver.getProperty(REMOTE_PATH, String.class, null);

	}
}
